package com.puboot.module.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.puboot.common.util.*;
import com.puboot.module.model.*;
import com.puboot.module.service.*;
import com.puboot.module.vo.base.ResponseVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 给前台页面提供的接口，包括针对文章进行的添加评论、获取评论、增加浏览次数和点赞操作
 *
 * @author Linzhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Slf4j
@RestController
@RequestMapping("api")
@AllArgsConstructor
public class ApiController {
    private final LkComicService comicService;
    private final UserService userService;
    private final LocaleUtil localeUtil;
    private final LkChapterService chapterService;
    private final LkComicLangService comicLangService;
    private final LkChapterLangService chapterLangService;

    @PostMapping("/delete")
    public ResponseVo api(HttpServletRequest request, Integer comicId){
        comicLangService.remove((Wrappers.<LkComicLang>lambdaQuery().eq(LkComicLang::getComicId, comicId)));
        List<LkChapter> chapters = chapterService.list((Wrappers.<LkChapter>lambdaQuery().eq(LkChapter::getComicId, comicId)));
        for(LkChapter chapter:chapters){
            chapterLangService.remove((Wrappers.<LkChapterLang>lambdaQuery().eq(LkChapterLang::getChapterId, chapter.getId())));
        }
        chapterService.remove((Wrappers.<LkChapter>lambdaQuery().eq(LkChapter::getComicId, comicId)));
        comicService.deleteById(comicId);
        return ResultUtil.success("ok");
    }
    @PostMapping("/rank")
    public IPage<LkComic> rank(Integer page) {
        return comicService.rank(page,LocaleContextHolder.getLocale().getLanguage());
    }

    @PostMapping("/cate/{cate}")
    public IPage<LkComic> cate(Integer page,@PathVariable(value = "cate") Integer cate) {
        if(cate==0)
            return comicService.all(page,LocaleContextHolder.getLocale().getLanguage());
        else
            return comicService.cate(cate,page,LocaleContextHolder.getLocale().getLanguage());
    }


    /**
     * 【接口】注册
     * @param request
     * @param username
     * @param password1
     * @param password2
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public ResponseVo register(HttpServletRequest request, String username, String password1, String password2){
        User user = userService.selectByUsername(username);
        if (null != user) {
            //用户名已存在
            return ResultUtil.error(localeUtil.get("register.exist"));
        }
        User register = new User();
        register.setNickname(username);
        register.setUsername(username);
        register.setUserId(UUIDUtil.getUniqueIdByUUId());
        register.setStatus(CoreConst.STATUS_VALID);
        Date date = new Date();
        register.setCreateTime(date);
        register.setPassword(password1);
        register.setUpdateTime(date);
        register.setLastLoginTime(date);
        PasswordHelper.encryptPassword(register);
        int num = userService.register(register);
        if (num > 0) {
            //注册成功，请登录
            return ResultUtil.success(localeUtil.get("ok.register"));
        } else {
            //注册失败，请重试
            return ResultUtil.error(localeUtil.get("error.unknown"));
        }
    }
    @PostMapping("/username")
    @ResponseBody
    public ResponseVo register(HttpServletRequest request, String username){
        User user = userService.selectByUsername(username);
        if (null == user) {
            return ResultUtil.success("ok");
        }else{
            return ResultUtil.error("err");
        }
    }

    /**
     * 【接口】登录接口
     * @param request
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseVo login(HttpServletRequest request, String username, String password){
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            token.setRememberMe(true);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
        } catch (LockedAccountException e) {
            token.clear();
            return ResultUtil.error(localeUtil.get("error.password"));
        } catch (AuthenticationException e) {
            token.clear();
            return ResultUtil.error(localeUtil.get("error.unknown"));
        }
        userService.updateLastLoginTime((User) SecurityUtils.getSubject().getPrincipal());
        //登录成功
        return ResultUtil.success(localeUtil.get("ok.login"));
    }

}
